#    Copyright 2008, 2009 Tri-County Electric Cooperative, St. Matthews, South Carolina
#    This file is part of COOPIP.
#    COOPIP is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#    COOPIP is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#    You should have received a copy of the GNU General Public License
#    along with COOPIP.  If not, see <http://www.gnu.org/licenses/>.

import os
import datetime
import shutil

#************************BEGIN Add Include Files to Path************************
import sys
NeededPaths=['/opt/coopip/djangoproject/include', '/opt/coopip/djangoproject']
for path in NeededPaths:
    if(not path in sys.path):
        sys.path.append(path)
#************************END   Add Include Files to Path************************
from django.contrib.gis.geos import *
import os, time, psycopg2, datetime
#********************Setup psycopg2 and django section********************
PathDjangoRoot="/opt/coopip/"
if(not PathDjangoRoot in sys.path):
    sys.path.append(PathDjangoRoot)
from django.core.management import setup_environ
import djangoproject
from djangoproject import settings
setup_environ(settings)
from djangoproject.models import *
#********************Setup psycopg2 and django section********************

from django.template import Context, loader
from django.http import HttpResponse
from django import forms
import os
import datetime
import djangoproject.settings
import GIS

def GetOpenLayersZoom(station=None, span=None, Zoom=15, point=None, SRID=3857):
    if(point):
        point=point.transform(SRID, clone=True) 
        return "map.setCenter(new OpenLayers.LonLat(" + str(point.x) + ',' + str(point.y)  + "), " + str(Zoom) + ");" #Zoom into the point of the Station
    if(station):
        point=station.Point.transform(SRID, clone=True)
        return "map.setCenter(new OpenLayers.LonLat(" + str(point.x) + ',' + str(point.y)  + "), " + str(Zoom) + ");" #Zoom into the point of the Station
    elif(span):
        PointCoordinates=span.Line[0]
        point=Point(x=PointCoordinates[0], y=PointCoordinates[1])
        point.srid=span.Line.srid
        point=point.transform(SRID, clone=True)
        return "map.setCenter(new OpenLayers.LonLat(" + str(point.x) +',' + str(point.y)  + "), " + str(Zoom) + ");" #Zoom into the point of the Station
    else:
        return "map.setCenter(new OpenLayers.LonLat(-8985500, 4000500), 13);"


def GetLatitudeLongitude(station=None, span=None, point=None, SRID=3857):
    if(point):
        point=point.transform(SRID, clone=True) 
        return point.x, point.y
    if(station):
        point=station.Point.transform(SRID, clone=True)
        return point.x, point.y
    elif(span):
        PointCoordinates=span.Line[0]
        point=Point(x=PointCoordinates[0], y=PointCoordinates[1])
        point.srid=span.Line.srid
        point=point.transform(SRID, clone=True)
        return point.x, point.y
    else:
        point=GIS.Coopgisstation.objects.all()[0].the_geom.transform(SRID, clone=True)
        return point.x, point.y

def GetOpenLayersJavaScriptHeading():
    return """<script src="/openlayers/lib/OpenLayers.js"></script>
    <script src="http://maps.google.com/maps/api/js?v=3.2&sensor=false"></script>"""


def GetOpenLayersJavaScript():
    return """  <script defer="defer" type="text/javascript">
    var bnd = new OpenLayers.Bounds(-9040000, 3940000, -8931000, 4061000);
   
    var options = {projection: new OpenLayers.Projection("EPSG:3857"),
        displayProjection: new OpenLayers.Projection("EPSG:4326"),
        units: "m",
        numZoomLevels: 22,
        maxResolution: 'auto', 
        maxExtent: bnd,
        'tileSize': new OpenLayers.Size(1024,768),
        'buffer':0};
       
    var map = new OpenLayers.Map('map', options);
    var emap = new OpenLayers.Layer.MapServer("Meter", 
                  "/cgi-bin/mapserv?MAP=/opt/coopip/mapserver/coopip.map",
                  {Layers:"Meter"},
		   {'buffer':0, 
                   'sphericalMercator': 'true',
                  'projection': new OpenLayers.Projection("EPSG:3857"),
                   visibility: true,
                   isBaseLayer: false});

    var serviceorder = new OpenLayers.Layer.MapServer("ServiceOrder", 
                  "/cgi-bin/mapserv?MAP=/opt/coopip/mapserver/coopipserviceorder.map",
                  {Layers:"ServiceOrder"},
		   {'buffer':0, 
                   'sphericalMercator': 'true',
                  'projection': new OpenLayers.Projection("EPSG:3857"),
                   visibility: false,
                   isBaseLayer: false});

    var failedmeter = new OpenLayers.Layer.MapServer("FailedMeter", 
                  "/cgi-bin/mapserv?MAP=/opt/coopip/mapserver/coopipfailedmeter.map",
                  {Layers:"FailedMeter"},
		   {'buffer':0, 
                   'sphericalMercator': 'true',
                  'projection': new OpenLayers.Projection("EPSG:3857"),
                   visibility: true,
                   isBaseLayer: false});

    var activebut = new OpenLayers.Layer.MapServer("MeterNotAuthorized", 
                  "/cgi-bin/mapserv?MAP=/opt/coopip/mapserver/coopipactivebutnotauthorized.map",
                  {Layers:"MeterActiveButNotAuthorized"},
		   {'buffer':0, 
                   'sphericalMercator': 'true',
                   'projection': new OpenLayers.Projection("EPSG:3857"),
                   visibility: true,
                   isBaseLayer: false});

    var investigation = new OpenLayers.Layer.MapServer("MeterInvestigation", 
                  "/cgi-bin/mapserv?MAP=/opt/coopip/mapserver/coopipinvestigationmeter.map",
                  {Layers:"MeterInvestigation"},
		   {'buffer':0, 
                   'sphericalMercator': 'true',
                   'projection': new OpenLayers.Projection("EPSG:3857"),
                   visibility: false,
                   isBaseLayer: false});

    var investigation = new OpenLayers.Layer.MapServer("MeterEquipmentFailure", 
                  "/cgi-bin/mapserv?MAP=/opt/coopip/mapserver/coopipsubstation_equipmentfailure.map",
                  {Layers:"MeterAMRFailure"},
		   {'buffer':0, 
                   'sphericalMercator': 'true',
                   'projection': new OpenLayers.Projection("EPSG:3857"),
                   visibility: true,
                   isBaseLayer: false});




    var gsat = new OpenLayers.Layer.Google("Google Satellite", {type: google.maps.MapTypeId.SATELLITE, numZoomLevels: 22});
    var gmap = new OpenLayers.Layer.Google("Google Streets", {numZoomLevels: 22});
    var gphy = new OpenLayers.Layer.Google("Google Physical",{type: google.maps.MapTypeId.TERRAIN});
    var ghyb = new OpenLayers.Layer.Google("Google Hybrid",{type: google.maps.MapTypeId.HYBRID, numZoomLevels: 22});




    var truck = new OpenLayers.Layer.MapServer("Truck", 
                  "/cgi-bin/mapserv?MAP=/opt/coopip/mapserver/truck.map",
                  {Layers:"Truck"},
		   {'buffer':0, 
                   'sphericalMercator': 'true',
                  'projection': new OpenLayers.Projection("EPSG:3857"),
                   visibility: false,
                   isBaseLayer: false});
               

    var meterblinkrecent = new OpenLayers.Layer.MapServer("MeterBlinkRecent", 
                  "/cgi-bin/mapserv?MAP=/opt/coopip/mapserver/allmeterscoopipmeterblinkrecent.map",
                  {Layers:"MeterBlinkRecent"},
		   {'buffer':0, 
                   'sphericalMercator': 'true',
                   'projection': new OpenLayers.Projection("EPSG:3857"),
                   visibility: false,
                   isBaseLayer: false});

    var phasing = new OpenLayers.Layer.MapServer("Phasing",
                  "/cgi-bin/mapserv?MAP=/opt/coopip/mapserver/coopgisphasing.map",
                  {Layers:"PhasingPrimaryOverhead, PhasingSecondaryOverhead, PhasingSecondaryUnderground, PhasingPrimaryUnderground"}, 
                  {'buffer':0,
                   'sphericalMercator': 'true',
                  'projection': new OpenLayers.Projection("EPSG:3857"),
                   visibility: false,
                   isBaseLayer: false});
                  

    var optionsforgraphic = {numZoomLevels: 22, maxResolution: 10000000, minResolution: 0.1};
    var graphic = new OpenLayers.Layer.Image('Background',
         '/mapbackground.png',
         bnd,
         new OpenLayers.Size(1024, 1024),
         optionsforgraphic);
    graphic.events.on({loadstart: function() {OpenLayers.Console.log("loadstart");},
                                              loadend: function() {
                                              OpenLayers.Console.log("loadend");}});
    map.addLayers([graphic, gsat, gmap, gphy, ghyb, emap, truck, serviceorder, failedmeter, activebut, investigation, meterblinkrecent, phasing]);
    map.addControl(new OpenLayers.Control.LayerSwitcher());
    map.addControl(new OpenLayers.Control.Permalink());
    map.addControl(new OpenLayers.Control.MousePosition());
    if (!map.getCenter()) {map.zoomToExtent(bnd)}

	  
  </script>"""




def GetAllMetersOpenLayersJavaScript(Top=True):
    String= """  <script defer="defer" type="text/javascript">
    var bnd = new OpenLayers.Bounds(-9540000, 3540000, -8038000, 4551000);
   
    var options = {projection: new OpenLayers.Projection("EPSG:3857"),
        displayProjection: new OpenLayers.Projection("EPSG:4326"),
        units: "m",
        numZoomLevels: 22,
        maxResolution: 'auto', 
        maxExtent: bnd,
        'tileSize': new OpenLayers.Size(1024,768),
        'buffer':0};
       
    var map = new OpenLayers.Map('map', options);
    var emap = new OpenLayers.Layer.MapServer("Meter", 
                  "/cgi-bin/mapserv?MAP=/opt/coopip/mapserver/allmeterscoopip.map",
                  {Layers:"Meter"},
		   {'buffer':0, 
                   'sphericalMercator': 'true',
                  'projection': new OpenLayers.Projection("EPSG:3857"),
                   visibility: true,
                   isBaseLayer: false});

    var serviceorder = new OpenLayers.Layer.MapServer("ServiceOrder", 
                  "/cgi-bin/mapserv?MAP=/opt/coopip/mapserver/allmeterscoopipserviceorder.map",
                  {Layers:"ServiceOrder"},
		   {'buffer':0, 
                   'sphericalMercator': 'true',
                  'projection': new OpenLayers.Projection("EPSG:3857"),
                   visibility: false,
                   isBaseLayer: false});

    var failedmeter = new OpenLayers.Layer.MapServer("FailedMeter", 
                  "/cgi-bin/mapserv?MAP=/opt/coopip/mapserver/allmeterscoopipfailedmeter.map",
                  {Layers:"FailedMeter"},
		   {'buffer':0, 
                   'sphericalMercator': 'true',
                  'projection': new OpenLayers.Projection("EPSG:3857"),
                   visibility: true,
                   isBaseLayer: false});

    var activebut = new OpenLayers.Layer.MapServer("MeterActiveButNotAuthorized", 
                  "/cgi-bin/mapserv?MAP=/opt/coopip/mapserver/allmeterscoopipactivebutnotauthorized.map",
                  {Layers:"MeterActiveButNotAuthorized"},
		   {'buffer':0, 
                   'sphericalMercator': 'true',
                   'projection': new OpenLayers.Projection("EPSG:3857"),
                   visibility: false,
                   isBaseLayer: false});

    var investigation = new OpenLayers.Layer.MapServer("MeterInvestigation", 
                  "/cgi-bin/mapserv?MAP=/opt/coopip/mapserver/allmeterscoopipinvestigationmeter.map",
                  {Layers:"MeterInvestigation"},
		   {'buffer':0, 
                   'sphericalMercator': 'true',
                   'projection': new OpenLayers.Projection("EPSG:3857"),
                   visibility: false,
                   isBaseLayer: false});


    var meterblinkrecent = new OpenLayers.Layer.MapServer("MeterBlinkRecent", 
                  "/cgi-bin/mapserv?MAP=/opt/coopip/mapserver/allmeterscoopipmeterblinkrecent.map",
                  {Layers:"MeterBlinkRecent"},
		   {'buffer':0, 
                   'sphericalMercator': 'true',
                   'projection': new OpenLayers.Projection("EPSG:3857"),
                   visibility: false,
                   isBaseLayer: false});



    var gsat = new OpenLayers.Layer.Google("Google Satellite", {type: google.maps.MapTypeId.SATELLITE, numZoomLevels: 22});
    var gmap = new OpenLayers.Layer.Google("Google Streets", {numZoomLevels: 28});
    var gphy = new OpenLayers.Layer.Google("Google Physical",{type: google.maps.MapTypeId.TERRAIN});
    var ghyb = new OpenLayers.Layer.Google("Google Hybrid",{type: google.maps.MapTypeId.HYBRID, numZoomLevels: 22});




    var truck = new OpenLayers.Layer.MapServer("Truck", 
                  "/cgi-bin/mapserv?MAP=/opt/coopip/mapserver/truck.map",
                  {Layers:"Truck"},
		   {'buffer':0, 
                   'sphericalMercator': 'true',
                  'projection': new OpenLayers.Projection("EPSG:3857"),
                   visibility: true,
                   isBaseLayer: false});



    var road = new OpenLayers.Layer.MapServer("Road", 
                  "/cgi-bin/mapserv?MAP=/opt/coopip/mapserver/road.map",
                  {Layers:"Road"},
		   {'buffer':0, 
                   'sphericalMercator': 'true',
                  'projection': new OpenLayers.Projection("EPSG:3857"),
                   visibility: true,
                   isBaseLayer: false});

    var phasing = new OpenLayers.Layer.MapServer("Phasing",
                  "/cgi-bin/mapserv?MAP=/opt/coopip/mapserver/coopgisphasing.map",
                  {Layers:"PhasingPrimaryOverhead, PhasingSecondaryOverhead, PhasingSecondaryUnderground, PhasingPrimaryUnderground"}, 
                  {'buffer':0,
                   'sphericalMercator': 'true',
                  'projection': new OpenLayers.Projection("EPSG:3857"),
                   visibility: false,
                   isBaseLayer: false});

    var trucklog = new OpenLayers.Layer.MapServer("TruckLog",
                  "/cgi-bin/mapserv?MAP=/opt/coopip/mapserver/trucklog.map",
                  {Layers:"TruckLog"},
                  {'buffer':0,
                   'sphericalMercator': 'true',
                  'projection': new OpenLayers.Projection("EPSG:3857"),
                   visibility: true,
                   isBaseLayer: false});
               
    var optionsforgraphic = {numZoomLevels: 20, maxResolution: 10000000, minResolution: 0.1};
    var graphic = new OpenLayers.Layer.Image('Background',
         '/mapbackground.png',
         bnd,
         new OpenLayers.Size(2048, 2048),
         optionsforgraphic);
    graphic.events.on({loadstart: function() {OpenLayers.Console.log("loadstart");},
                                              loadend: function() {
                                              OpenLayers.Console.log("loadend");}});
    map.addLayers([graphic,  road, gsat, gmap, gphy, ghyb, emap, truck, serviceorder, failedmeter, activebut, investigation, meterblinkrecent, phasing, trucklog]);
    map.addControl(new OpenLayers.Control.LayerSwitcher());
    map.addControl(new OpenLayers.Control.Permalink());
    map.addControl(new OpenLayers.Control.MousePosition());
    if (!map.getCenter()) {map.zoomToExtent(bnd)}
    """  
    CenterX=-9002541.20776
    CenterY=4038503.90054
    if(Top):
        String=String + 'map.setCenter(new OpenLayers.LonLat(' + str(CenterX + 5000) + ',' + str(CenterY - 32000) + '), 12);</script>'
        
    else:
        String=String + 'map.setCenter(new OpenLayers.LonLat(' + str(CenterX + 31000) + ',' + str(CenterY - 85000) + '), 12);</script>'
    return String













def GetDispatchDisplayMapJavaScript():
    String= """  <script defer="defer" type="text/javascript">
    var bnd = new OpenLayers.Bounds(-9540000, 3540000, -8038000, 4551000);
   
    var options = {projection: new OpenLayers.Projection("EPSG:3857"),
        displayProjection: new OpenLayers.Projection("EPSG:4326"),
        units: "m",
        numZoomLevels: 22,
        maxResolution: 'auto', 
        maxExtent: bnd,
        'tileSize': new OpenLayers.Size(1024,768),
        'buffer':0};
       
    var map = new OpenLayers.Map('map', options);


    var serviceorder = new OpenLayers.Layer.MapServer("ServiceOrder", 
                  "/cgi-bin/mapserv?MAP=/opt/coopip/mapserver/allmeterscoopipserviceorder.map",
                  {Layers:"ServiceOrder"},
		   {'buffer':0, 
                   'sphericalMercator': 'true',
                  'projection': new OpenLayers.Projection("EPSG:3857"),
                   visibility: false,
                   isBaseLayer: false});

    var failedmeter = new OpenLayers.Layer.MapServer("FailedMeter", 
                  "/cgi-bin/mapserv?MAP=/opt/coopip/mapserver/allmeterscoopipfailedmeter.map",
                  {Layers:"FailedMeter"},
		   {'buffer':0, 
                   'sphericalMercator': 'true',
                  'projection': new OpenLayers.Projection("EPSG:3857"),
                   visibility: true,
                   isBaseLayer: false});

    var activebut = new OpenLayers.Layer.MapServer("MeterActiveButNotAuthorized", 
                  "/cgi-bin/mapserv?MAP=/opt/coopip/mapserver/allmeterscoopipactivebutnotauthorized.map",
                  {Layers:"MeterActiveButNotAuthorized"},
		   {'buffer':0, 
                   'sphericalMercator': 'true',
                   'projection': new OpenLayers.Projection("EPSG:3857"),
                   visibility: false,
                   isBaseLayer: false});

    var investigation = new OpenLayers.Layer.MapServer("MeterInvestigation", 
                  "/cgi-bin/mapserv?MAP=/opt/coopip/mapserver/allmeterscoopipinvestigationmeter.map",
                  {Layers:"MeterInvestigation"},
		   {'buffer':0, 
                   'sphericalMercator': 'true',
                   'projection': new OpenLayers.Projection("EPSG:3857"),
                   visibility: false,
                   isBaseLayer: false});


    var meterblinkrecent = new OpenLayers.Layer.MapServer("MeterBlinkRecent", 
                  "/cgi-bin/mapserv?MAP=/opt/coopip/mapserver/allmeterscoopipmeterblinkrecent.map",
                  {Layers:"MeterBlinkRecent"},
		   {'buffer':0, 
                   'sphericalMercator': 'true',
                   'projection': new OpenLayers.Projection("EPSG:3857"),
                   visibility: false,
                   isBaseLayer: false});



    var gsat = new OpenLayers.Layer.Google("Google Satellite", {type: google.maps.MapTypeId.SATELLITE, numZoomLevels: 22});
    var gmap = new OpenLayers.Layer.Google("Google Streets", {numZoomLevels: 28});
    var gphy = new OpenLayers.Layer.Google("Google Physical",{type: google.maps.MapTypeId.TERRAIN});
    var ghyb = new OpenLayers.Layer.Google("Google Hybrid",{type: google.maps.MapTypeId.HYBRID, numZoomLevels: 22});




    var truck = new OpenLayers.Layer.MapServer("Truck", 
                  "/cgi-bin/mapserv?MAP=/opt/coopip/mapserver/truck.map",
                  {Layers:"Truck"},
		   {'buffer':0, 
                   'sphericalMercator': 'true',
                  'projection': new OpenLayers.Projection("EPSG:3857"),
                   visibility: true,
                   isBaseLayer: false});



    var road = new OpenLayers.Layer.MapServer("Road", 
                  "/cgi-bin/mapserv?MAP=/opt/coopip/mapserver/road.map",
                  {Layers:"Road"},
		   {'buffer':0, 
                   'sphericalMercator': 'true',
                  'projection': new OpenLayers.Projection("EPSG:3857"),
                   visibility: true,
                   isBaseLayer: false});

    var phasing = new OpenLayers.Layer.MapServer("Phasing",
                  "/cgi-bin/mapserv?MAP=/opt/coopip/mapserver/coopgisphasing.map",
                  {Layers:"PhasingPrimaryOverhead, PhasingSecondaryOverhead, PhasingSecondaryUnderground, PhasingPrimaryUnderground"}, 
                  {'buffer':0,
                   'sphericalMercator': 'true',
                  'projection': new OpenLayers.Projection("EPSG:3857"),
                   visibility: false,
                   isBaseLayer: false});


               
    var optionsforgraphic = {numZoomLevels: 20, maxResolution: 10000000, minResolution: 0.1};
    var graphic = new OpenLayers.Layer.Image('Background',
         '/mapbackground.png',
         bnd,
         new OpenLayers.Size(2048, 2048),
         optionsforgraphic);
    graphic.events.on({loadstart: function() {OpenLayers.Console.log("loadstart");},
                                              loadend: function() {
                                              OpenLayers.Console.log("loadend");}});
    map.addLayers([graphic,  road, gsat, gmap, gphy, ghyb,  truck, serviceorder, failedmeter, activebut, investigation, meterblinkrecent, phasing]);
    map.addControl(new OpenLayers.Control.LayerSwitcher());
    map.addControl(new OpenLayers.Control.Permalink());
    map.addControl(new OpenLayers.Control.MousePosition());
    if (!map.getCenter()) {map.zoomToExtent(bnd)}
    """  
    CenterX=-9002541.20776
    CenterY=4038503.90054
    String=String + 'map.setCenter(new OpenLayers.LonLat(' + str(CenterX + 25000) + ',' + str(CenterY - 42000) + '), 12);</script>'
    return String

def GetVehicleLogDisplayMapJavaScript(MapFileName):
    String = """<script defer="defer" type="text/javascript">
    var bnd = new OpenLayers.Bounds(-9040000, 3940000, -8931000, 4061000);
   
    var options = {projection: new OpenLayers.Projection("EPSG:3857"),
        displayProjection: new OpenLayers.Projection("EPSG:4326"),
        units: "m",
        numZoomLevels: 22,
        maxResolution: 'auto', 
        maxExtent: bnd,
        'tileSize': new OpenLayers.Size(1024,768),
        'buffer':0};
       
    var map = new OpenLayers.Map('map', options);



    var vehiclelog = new OpenLayers.Layer.MapServer("VehicleLog", 
                  "/cgi-bin/mapserv?MAP={{MapFileName}}",
                  {Layers:"VehicleLog"},
		   {'buffer':0, 
                   'sphericalMercator': 'true',
                  'projection': new OpenLayers.Projection("EPSG:3857"),
                   visibility: true,
                   isBaseLayer: false});


    var road = new OpenLayers.Layer.MapServer("Road", 
                  "/cgi-bin/mapserv?MAP=/opt/coopip/mapserver/road.map",
                  {Layers:"Road"},
		   {'buffer':0, 
                   'sphericalMercator': 'true',
                  'projection': new OpenLayers.Projection("EPSG:3857"),
                   visibility: true,
                   isBaseLayer: false});

               
                

    var optionsforgraphic = {numZoomLevels: 22, maxResolution: 10000000, minResolution: 0.1};
    var graphic = new OpenLayers.Layer.Image('Background',
         '/mapbackground.png',
         bnd,
         new OpenLayers.Size(1024, 1024),
         optionsforgraphic);
    graphic.events.on({loadstart: function() {OpenLayers.Console.log("loadstart");},
                                              loadend: function() {
                                              OpenLayers.Console.log("loadend");}});
    map.addLayers([graphic, road, vehiclelog]);
    map.addControl(new OpenLayers.Control.LayerSwitcher());
    map.addControl(new OpenLayers.Control.Permalink());
    map.addControl(new OpenLayers.Control.MousePosition());
    if (!map.getCenter()) {map.zoomToExtent(bnd)}
    map.setCenter(new OpenLayers.LonLat(-8977541.20776,3996503.90054), 13);
    </script>""".replace('{{MapFileName}}', MapFileName)
    return String
